2023/12/234027字符
React 生命周期
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Comp extends Component {
// 1. 初始化,同一组件对象只会创建一次
constructor (props) {
super(props);
this.state = {
n: 0
}
// console.log(this.setState()); // 组件还未挂载,不能调用 this.setState
}
// 2. 更新阶段,重新渲染之前调用,获取新的属性和状态
static getDerivedStateFromProps (props, state) { // 静态函数,无法调用 this
console.log(props, state);
return { // 通过返回值来控制 state,拦截
n: 1
};
}
// 3*. 渲染函数,多次执行(严禁使用 this.setState)
render () {
return (<>hello {this.state.n}</>);
}
// 4*. 数据发生改变执行,可以使用 this.setState,只执行一次
componentDidMount () {
this.setState({n: 2, x: 1})
// 通常会将网络请求、启动计时器等操作放入该函数中
}
// 6*. 状态发生改变,可以得到改变之后的属性、状态
shouldComponentUpdate (nextProps, nextState) {
if (this.props === nextProps && this.state === nextState) { // 性能优化:属性&状态未改变,不进行渲染
return false;
}
return true; // 要求必须返回一个 bool 值,指示 React 是否重新渲染
}
// 7. 虚拟 DOM 树构建完成,但还未渲染到页面中
getSnapshotBeforeUpdate (prevProps, prevState) {
console.log(prevProps, prevState);
return 111; // 返回值会作为 componentDidUpdate 的第三个参数
}
// 8. 更新阶段,可以得到之前的状态
componentDidUpdate (prevProps, prevState, snap) {
// 改变元素,DOM 操作
console.log(snap)
}
// 9*. 组件销毁
componentWillUnmount () {
// 清除计时器
}
}
ReactDOM.render(<Comp />, document.getElementById('root'));
旧版生命周期 (16.0.0 以下)
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Comp extends Component {
// 1. 初始化,同一组件对象只会创建一次
constructor (props) {
super(props);
this.state = {
n: 0
}
// console.log(this.setState()); // 组件还未挂载,不能调用 this.setState
}
// 2. 组件即将被挂载,只运行一次
componentWillMount () {
// 可以使用 this.setState 但不允许使用,存在一些 bug
}
// 3*. 渲染函数,多次执行(严禁使用 this.setState)
render () {
return (<>hello {this.state.n}</>);
}
// 4*. 数据发生改变执行,可以使用 this.setState,只执行一次
componentDidMount () {
this.setState({n: 2, x: 1})
// 通常会将网络请求、启动计时器等操作放入该函数中
}
// 5. 属性发生变化,可以得到改变之后的属性
componentWillReceiveProps (nextProps) {
console.log(nextProps);
}
// 6*. 状态发生改变,可以得到改变之后的属性、状态
shouldComponentUpdate (nextProps, nextState) {
if (this.props === nextProps && this.state === nextState) { // 性能优化:属性&状态未改变,不进行渲染
return false;
}
return true; // 要求必须返回一个 bool 值,指示 React 是否重新渲染
}
// 7. 组件即将被渲染
componentWillUpdate (nextProps, nextState) {}
// 8. 更新阶段,可以得到之前的状态
componentDidUpdate (prevProps, prevState) {
// 改变元素,Dom 操作
}
// 9*. 组件销毁
componentWillUnmount () {
// 清除计时器
}
}
ReactDOM.render(<Comp />, document.getElementById('root'));